﻿namespace Engine.Serialization
{
    using System;
    using System.Reflection;

    public class SerializerFactory
    {
        #region [Attributes]
        private static volatile SerializerFactory instance;
        private static object syncRoot = new object();
        private const string adapterSuffix = "SerializerAdapter";
        #endregion

        #region [Properties]
        public static SerializerFactory Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new SerializerFactory();
                        }
                    }
                }

                return instance;
            }
        }
        #endregion

        #region [Methods]
        /// <summary>
        /// Constructor
        /// </summary>
        private SerializerFactory() { }

        /// <summary>
        /// Get a Serialiser for given Type
        /// </summary>
        /// <typeparam name="T">Type managed by the Serializer</typeparam>
        /// <param name="type">Type of Serializer</param>
        /// <returns>Requested Serializer</returns>
        public ISerializer<T> GetSerializer<T>(DataType type)
            where T : class
        {
            // All Serializers must be in the same namespace as the interface 'ISerializer<T>'
            string adapterTypeName = string.Concat(typeof(ISerializer<T>).Namespace, ".", type.ToString(), adapterSuffix);

            Type adapterType = Type.GetType(string.Concat(adapterTypeName, "`1[[", typeof(T).AssemblyQualifiedName, "]]"));

            ISerializer<T> serializer = Activator.CreateInstance(adapterType) as ISerializer<T>;

            return serializer;
        }
        #endregion
    }
}
